using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

namespace LS
{
    public abstract class MouseClickState : PlayerInputHolder.InputState
    {
        protected InputPhase m_Phase = InputPhase.Non;
        protected bool m_IsPressed = false;
        protected float m_StartTime = 0;
        protected float m_PreviousTime = 0;

        protected Vector2 m_StartPoint;
        protected Vector2 m_PreviousPoint;

        protected MouseClickState(PlayerInputHolder.InputSetting setting) : base(setting)
        {
        }

        public override InputPhase Phase => m_Phase;

        public override bool IsPressed => m_IsPressed;

        public override float Duration => m_PreviousTime - m_StartTime;

        public Vector2 StartPoint => m_StartPoint;
        public Vector2 PreviousPoint => m_PreviousPoint;

        public float DistanceSq => (PreviousPoint - StartPoint).sqrMagnitude;

        public override void OnUpdate()
        {
            var control = GetControl();
            if (control.isPressed)
            {
                if (control.wasPressedThisFrame)
                {
                    m_Phase = InputPhase.Start;
                    m_StartTime = Time.unscaledTime;
                    m_StartPoint = Mouse.current.position.ReadValue();
                }
                else
                {
                    m_Phase = InputPhase.Update;
                    m_PreviousTime = Time.unscaledTime;
                    m_PreviousPoint = Mouse.current.position.ReadValue();
                }
            }
            else
            {
                if (control.wasReleasedThisFrame)
                {
                    m_Phase = InputPhase.End;
                    m_PreviousTime = Time.unscaledTime;
                    m_PreviousPoint = Mouse.current.position.ReadValue();
                }
                else
                {
                    m_Phase = InputPhase.Non;
                    m_StartTime = 0;
                    m_PreviousTime = 0;
                    m_StartPoint = Vector2.zero;
                    m_PreviousPoint = Vector2.zero;
                }
            }

            m_IsPressed = IsPressedThisFrame();
        }

        public virtual bool IsPressedThisFrame()
        {
            return m_Phase == InputPhase.End && DistanceSq <= Setting.TapDuration;
        }

        public abstract ButtonControl GetControl();
    }
}
